Introduction to Python Functions

Because copy-pasting code is so last semester

Danilo Freire

Emory University

February 07, 2025

Hello, everyone!
Hope you’re doing well today 😉

Lecture outline

  • Introduction: Why functions?
    • Stop code repetition (DRY, organisation)
  • What are Python functions?
    • def keyword and reusable code blocks
  • Function syntax
    • Function anatomy: name, parameters, body, return, indent
  • Function parameters
    • Positional vs keyword arguments, default values, *args, and **kwargs
  • Best practices and pitfalls
    • Naming, docstrings, indent, return errors
  • Summary and next steps
    • Recap and Q&A

Let’s get started! 🚀

Why functions?

  • The problem: code repetition is a trap!
    • Imagine writing the same code…
    • … again and again and again! 😩
  • An example: greeting many people
    • See the code on the right… Imagine doing this for 1000 names!
  • Inefficient and error-prone
  • Harder to read and maintain
  • Code becomes long and messy
  • Maybe there’s a better way to do this? 🤔
# Greeting people (without functions)
# Don't do this at home!

print("Nice to meet you, Alice!")
print("Nice to meet you, Bob!")
print("Nice to meet you, Charlie!")
print("Nice to meet you, Danilo!")
print("Nice to meet you, Emily!")
print("Nice to meet you, Frank!")
print("Nice to meet you, George!")

# ... and so on for 1000 names...

Yes, there is!

Introducing Python functions

  • Functions are like mini-programs
    • Self-contained blocks of code
    • Designed to perform a specific task
  • Think of them as “recipes” for code: 🧑‍🍳
    • You define the steps (code inside the function)
    • You can “call” the function (use the recipe) whenever you need to perform that task
  • Why are they useful?
    • Solve code repetition (as we saw!)
    • Organise your code into logical blocks
    • They are reusable – write once, use many times
    • DRY principle: Don’t Repeat Yourself 😉
# Greeting people (with functions)
# Much better!

def greet(name):
    print(f"Nice to meet you, {name}!")

greet("Alice")
greet("Bob")
greet("Charlie")
greet("Danilo")
Nice to meet you, Alice!
Nice to meet you, Bob!
Nice to meet you, Charlie!
Nice to meet you, Danilo!